package com.pethospital.servlet;

import com.pethospital.entity.User;
import com.pethospital.service.AppointmentService;
import com.pethospital.service.HealthRecordService;
import com.pethospital.service.PetService;
import com.pethospital.service.UserService;
import com.pethospital.service.impl.AppointmentServiceImpl;
import com.pethospital.service.impl.HealthRecordServiceImpl;
import com.pethospital.service.impl.PetServiceImpl;
import com.pethospital.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 仪表盘控制器
 * Dashboard Controller Servlet
 * 
 * @author PetHospital System
 * @version 1.0
 */
public class DashboardServlet extends HttpServlet {
    
    private UserService userService = new UserServiceImpl();
    private PetService petService = new PetServiceImpl();
    private AppointmentService appointmentService = new AppointmentServiceImpl();
    private HealthRecordService healthRecordService = new HealthRecordServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        
        // 检查用户登录状态
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录");
            return;
        }
        
        // 从URL路径获取操作类型
        String pathInfo = request.getPathInfo();
        String action = pathInfo != null ? pathInfo.substring(1) : "stats";
        
        try {
            switch (action) {
                case "stats":
                    handleGetStats(request, response, currentUser);
                    break;
                case "today-stats":
                    handleGetTodayStats(request, response, currentUser);
                    break;
                case "recent-activities":
                    handleGetRecentActivities(request, response, currentUser);
                    break;
                default:
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的操作");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误");
        }
    }
    
    /**
     * 获取总体统计数据
     */
    private void handleGetStats(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        
        PrintWriter writer = response.getWriter();
        
        try {
            // 获取统计数据
            long userCount = 0;
            long petCount = 0;
            long appointmentCount = 0;
            long recordCount = 0;
            
            if ("admin".equals(currentUser.getUserType())) {
                // 管理员可以看到所有数据
                userCount = userService.getTotalUserCount();
                petCount = petService.getTotalPetCount();
                appointmentCount = appointmentService.getTotalAppointmentCount();
                recordCount = healthRecordService.getTotalHealthRecordsCount();
            } else {
                // 普通用户只能看到自己的数据
                petCount = petService.getPetCountByOwner(currentUser.getUserId());
                appointmentCount = appointmentService.getAppointmentCountByOwner(currentUser.getUserId());
                recordCount = healthRecordService.getHealthRecordsCountByOwnerId(currentUser.getUserId());
            }
            
            // 构建JSON响应
            StringBuilder json = new StringBuilder();
            json.append("{");
            json.append("\"userCount\":").append(userCount).append(",");
            json.append("\"petCount\":").append(petCount).append(",");
            json.append("\"appointmentCount\":").append(appointmentCount).append(",");
            json.append("\"recordCount\":").append(recordCount);
            json.append("}");
            
            writer.write(json.toString());
            
        } catch (Exception e) {
            e.printStackTrace();
            writer.write("{\"error\":\"获取统计数据失败\"}");
        } finally {
            writer.close();
        }
    }
    
    /**
     * 获取今日统计数据
     */
    private void handleGetTodayStats(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {
        
        PrintWriter writer = response.getWriter();
        
        try {
            // 获取今日统计数据
            long todayUsers = 0;
            long todayPets = 0;
            long todayAppointments = 0;
            long pendingAppointments = 0;
            
            if ("admin".equals(currentUser.getUserType())) {
                // 管理员可以看到所有数据
                todayUsers = userService.getTodayRegisteredUserCount();
                todayPets = petService.getTodayRegisteredPetCount();
                todayAppointments = appointmentService.getTodayAppointmentCount();
                pendingAppointments = appointmentService.getPendingAppointmentCount();
            } else {
                // 普通用户只能看到自己的数据
                todayPets = petService.getTodayRegisteredPetCountByOwnerId(currentUser.getUserId());
                todayAppointments = appointmentService.getTodayAppointmentCountByOwnerId(currentUser.getUserId());
                pendingAppointments = appointmentService.getPendingAppointmentCountByOwnerId(currentUser.getUserId());
            }
            
            // 构建JSON响应
            StringBuilder json = new StringBuilder();
            json.append("{");
            json.append("\"todayUsers\":").append(todayUsers).append(",");
            json.append("\"todayPets\":").append(todayPets).append(",");
            json.append("\"todayAppointments\":").append(todayAppointments).append(",");
            json.append("\"pendingAppointments\":").append(pendingAppointments);
            json.append("}");
            
            writer.write(json.toString());
            
        } catch (Exception e) {
            e.printStackTrace();
            writer.write("{\"error\":\"获取今日统计数据失败\"}");
        } finally {
            writer.close();
        }
    }

    /**
     * 获取最近活动数据
     */
    private void handleGetRecentActivities(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {

        PrintWriter writer = response.getWriter();

        try {
            // 只获取普通用户的最近活动
            if ("admin".equals(currentUser.getUserType())) {
                writer.write("{\"error\":\"管理员暂不支持最近活动功能\"}");
                return;
            }

            // 获取最近的预约记录（最多5条）
            java.util.List<com.pethospital.entity.Appointment> recentAppointments =
                appointmentService.getRecentAppointmentsByOwnerId(currentUser.getUserId(), 5);

            // 获取最近添加的宠物（最多5条）
            java.util.List<com.pethospital.entity.Pet> recentPets =
                petService.getRecentPetsByOwnerId(currentUser.getUserId(), 5);

            // 构建JSON响应
            StringBuilder json = new StringBuilder();
            json.append("{\"activities\":[");

            // 合并预约和宠物数据，按时间排序
            java.util.List<ActivityItem> activities = new java.util.ArrayList<>();

            // 添加预约活动
            for (com.pethospital.entity.Appointment appointment : recentAppointments) {
                ActivityItem item = new ActivityItem();
                item.type = "appointment";
                item.title = "预约了" + appointment.getServiceType() + "服务";
                item.time = appointment.getCreateTime();
                item.icon = "fas fa-calendar-plus";
                item.iconColor = "linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)";
                activities.add(item);
            }

            // 添加宠物活动
            for (com.pethospital.entity.Pet pet : recentPets) {
                ActivityItem item = new ActivityItem();
                item.type = "pet";
                item.title = "添加了新宠物\"" + pet.getPetName() + "\"";
                item.time = pet.getCreateTime();
                item.icon = "fas fa-paw";
                item.iconColor = "linear-gradient(135deg, #f093fb 0%, #f5576c 100%)";
                activities.add(item);
            }

            // 按时间倒序排序
            activities.sort((a, b) -> b.time.compareTo(a.time));

            // 只取前5条
            if (activities.size() > 5) {
                activities = activities.subList(0, 5);
            }

            // 生成JSON
            for (int i = 0; i < activities.size(); i++) {
                ActivityItem item = activities.get(i);
                if (i > 0) json.append(",");

                json.append("{");
                json.append("\"type\":\"").append(item.type).append("\",");
                json.append("\"title\":\"").append(escapeJson(item.title)).append("\",");
                json.append("\"time\":\"").append(formatTimeAgo(item.time)).append("\",");
                json.append("\"icon\":\"").append(item.icon).append("\",");
                json.append("\"iconColor\":\"").append(item.iconColor).append("\"");
                json.append("}");
            }

            json.append("]}");

            writer.write(json.toString());

        } catch (Exception e) {
            e.printStackTrace();
            writer.write("{\"error\":\"获取最近活动失败\"}");
        } finally {
            writer.close();
        }
    }

    /**
     * 活动项内部类
     */
    private static class ActivityItem {
        String type;
        String title;
        java.util.Date time;
        String icon;
        String iconColor;
    }

    /**
     * 转义JSON字符串
     */
    private String escapeJson(String str) {
        if (str == null) return "";
        return str.replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r");
    }

    /**
     * 格式化时间为相对时间
     */
    private String formatTimeAgo(java.util.Date date) {
        if (date == null) return "未知时间";

        long now = System.currentTimeMillis();
        long diff = now - date.getTime();

        if (diff < 60 * 1000) {
            return "刚刚";
        } else if (diff < 60 * 60 * 1000) {
            return (diff / (60 * 1000)) + "分钟前";
        } else if (diff < 24 * 60 * 60 * 1000) {
            return (diff / (60 * 60 * 1000)) + "小时前";
        } else if (diff < 7 * 24 * 60 * 60 * 1000) {
            return (diff / (24 * 60 * 60 * 1000)) + "天前";
        } else {
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MM-dd");
            return sdf.format(date);
        }
    }
}
